package net.wanho.shiro.filter;

import cn.hutool.json.JSONUtil;
import net.wanho.shiro.token.JwtToken;
import net.wanho.vo.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.BearerToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * Author：汤小洋
 * Date：2023-10-16 10:29
 * Description：JWT过滤器
 */
public class JwtFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        HttpServletRequest request = WebUtils.toHttp(servletRequest);

        /**
         * 如果前端发送跨域请求，且自定义了请求头时，那么每次请求前会自动发起一个options预检请求，用来获取服务器信息
         * 这是浏览器自身的机制，该请求中不会含有token信息，所以对于options请求，直接放行
         */
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }

        // 判断请求头中是否有token，如果没有，则直接拒绝访问，如果有，则进行身份认证
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)){
            servletResponse.setContentType("application/json;charset=utf8");
            servletResponse.getWriter().write(JSONUtil.toJsonStr(AjaxResult.error("请先登录再操作！")));
            return false;
        }
        String token = authorization.replace("Bearer ", "");

        // 调用shiro认证
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new BearerToken(token));
        } catch (AuthenticationException e) {
            servletResponse.setContentType("application/json;charset=utf8");
            servletResponse.getWriter().write(JSONUtil.toJsonStr(AjaxResult.error("token无效，登录失败！")));
            return false;
        }

        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return false;
    }
}
